#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include <sys/types.h>
using namespace std;
int main()
{
    //1. 创建管道
    int pipefd[2] = {0};
    int fd_result = pipe(pipefd);
    if(fd_result == -1)
    {
        cout << "call pipe() is failed" << "errno=" << errno << ":" << strerror(errno) << endl;
    }
    cout << "pipefd[0]:" << pipefd[0] << endl;  //fd:3 -> 读端 
    cout << "pipefd[1]:" << pipefd[1] << endl;  //fd:4 -> 写端
    //2. 创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0) //child(写入)
    {
        close(pipefd[0]); //关闭读端
        //4. 开始通信
        const string name_str = "hello, i am child";
        int cnt = 1;
        char buffer_child[1024];
        while(true)
        {
            snprintf(buffer_child, sizeof(buffer_child), "name:%s, cnt:%d, my_pid:%d", name_str.c_str(), cnt++, getpid());
            write(pipefd[1], buffer_child, strlen(buffer_child));
            sleep(1);
        }
        exit(0);    
    }
    //parent(读取):
    //3. 关闭不需要的fd(父进程读取，子进程写入)
    close(pipefd[1]); //关闭写端
    char buffer_parent[1024];
    while(true)
    {
        int n = read(pipefd[0], buffer_parent, sizeof(buffer_parent) - 1);
        if(n == -1)
        {
            cout << "call read() is failed" << "errno=" << errno << ":" << strerror(errno) << endl;
        }
        buffer_parent[n] = '\0';
        cout << "i am parent, child give me message:" << buffer_parent << endl;
    }
    return 0;
}
